package menu;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Ellipse;
import javafx.stage.Stage;

// 场景菜单(适用于右键进行菜单选择,有的组件可以setContextMenu)
public class ContextMenuDemo extends Application {
	private Pane root = new Pane();
	private ContextMenu cm;
	
	public static void main(String[] args) {
	    launch(args);
	}
	
	@Override
	public void start(Stage stage) {
		
		cm = new ContextMenu();
	    MenuItem open = new MenuItem("Open");
	    open.setDisable(true);                  // 禁用，点击无反应
	    
	    MenuItem save = new MenuItem("Save");
	    save.setStyle("-fx-background-color: purple");
	    
	    MenuItem exit = new MenuItem("Exit");
	    exit.setAccelerator(KeyCombination.valueOf("Ctrl+a"));   // 设置快捷键(相当于点击)
	    exit.setOnAction(e -> stage.close());   // 关闭窗口
	    
	    // 自定义选项(自定义结点)
	    CustomMenuItem cmi = new CustomMenuItem();
	    cmi.setContent(new Ellipse(15, 10));
	    cm.getItems().addAll(open, save, new SeparatorMenuItem(), exit, cmi);    // exit和save之间增加一条分割线
	    
	    Scene scene = new Scene(root, 500, 400);
	    stage.setScene(scene);
	    stage.show();
	    
	    addEvents();
	}
	
	// 添加事件
	private void addEvents() {
		// 右键在鼠标处显示菜单
		root.setOnMouseClicked(e -> {
			if(e.getButton() == MouseButton.SECONDARY) {
				cm.show(root, e.getScreenX(), e.getScreenY());
			}
		});
	}
}